package com.dc.wifi.main.utils;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.dc.wifi.main.DCApplication;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ContinuousAPScanner {
    private static final String TAG = "ContinuousAPScanner";
    private static final long SCAN_INTERVAL = 10000; // 10 seconds

    private Context context;
    private WifiManager wifiManager;
    private BroadcastReceiver wifiScanReceiver;
    private Timer scanTimer;
    private List<ScanResult> latestScanResults;
    private OnScanResultsListener listener;

    public interface OnScanResultsListener {
        void onScanResults(List<ScanResult> results);
    }

    public ContinuousAPScanner(Context context) {
        this.context = context;
        this.wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        this.latestScanResults = new ArrayList<>();
        initWifiScanReceiver();
    }

    public void setOnScanResultsListener(OnScanResultsListener listener) {
        this.listener = listener;
    }

    public void startContinuousScanning() {
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        context.registerReceiver(wifiScanReceiver, intentFilter);

        scanTimer = new Timer();
        scanTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                wifiManager.startScan();
            }
        }, 0, SCAN_INTERVAL);
    }

    public void stopContinuousScanning() {
        if (scanTimer != null) {
            scanTimer.cancel();
            scanTimer = null;
        }
        try {
            context.unregisterReceiver(wifiScanReceiver);
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "Receiver not registered: " + e.getMessage());
        }
    }

    private void initWifiScanReceiver() {
        wifiScanReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                boolean success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);
                if (success) {
                    scanSuccess();
                } else {
                    scanFailure();
                }
            }
        };
    }

    private void scanSuccess() {
        if (ActivityCompat.checkSelfPermission(DCApplication.getInstance(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        latestScanResults = wifiManager.getScanResults();
        if (listener != null) {
            new Handler(context.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    listener.onScanResults(latestScanResults);
                }
            });
        }
    }

    private void scanFailure() {
        // 可以选择使用上一次的扫描结果，或者重新尝试扫描
        latestScanResults = wifiManager.getScanResults();
        if (listener != null) {
            new Handler(context.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    listener.onScanResults(latestScanResults);
                }
            });
        }
    }

    public List<ScanResult> getLatestScanResults() {
        return latestScanResults;
    }
}